package com.ruoyi.mall.product.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.constant.ProductConstant;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.mall.product.domain.entity.PmsAttr;
import com.ruoyi.mall.product.domain.entity.PmsAttrAttrgroupRelation;
import com.ruoyi.mall.product.domain.entity.PmsAttrGroup;
import com.ruoyi.mall.product.domain.entity.PmsCategory;
import com.ruoyi.mall.product.domain.repository.PmsAttrAttrgroupRelationMapper;
import com.ruoyi.mall.product.domain.repository.PmsAttrGroupMapper;
import com.ruoyi.mall.product.domain.repository.PmsAttrMapper;
import com.ruoyi.mall.product.domain.repository.PmsCategoryMapper;
import com.ruoyi.mall.product.domain.service.IPmsAttrGroupService;
import com.ruoyi.mall.product.domain.vo.PmsAttrGroupAttrsVo;
import com.ruoyi.mall.product.domain.vo.PmsAttrGroupVo;
import com.ruoyi.mall.product.domain.vo.TreeSelect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 属性分组Service业务层处理
 *
 * @author zhangqishu
 * @date 2022-05-25
 */
@Service
public class PmsAttrGroupServiceImpl implements IPmsAttrGroupService {
    @Autowired
    private PmsAttrGroupMapper pmsAttrGroupMapper;
    @Autowired
    private PmsCategoryMapper pmsCategoryMapper;

    @Autowired
    private PmsAttrMapper pmsAttrMapper;

    @Autowired
    private PmsAttrAttrgroupRelationMapper pmsAttrAttrgroupRelationMapper;

    /**
     * 查询属性分组
     *
     * @param id 属性分组主键
     * @return 属性分组
     */
    @Override
    public PmsAttrGroup selectPmsAttrGroupById(Long id) {
        return pmsAttrGroupMapper.selectById(id);
    }

    /**
     * 查询属性分组列表
     *
     * @return
     */
    @Override
    public List<PmsAttrGroup> selectPmsAttrGroupList(PmsAttrGroup pmsAttrGroup) {

        QueryWrapper<PmsAttrGroup> queryWrapper = new QueryWrapper<>();
        String key = pmsAttrGroup.getKey();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(i -> i.eq("id", key).or().like("name", key));
        }
        if (pmsAttrGroup.getCategoryId() == 0) {
            List<PmsAttrGroup> groups = pmsAttrGroupMapper.selectList(queryWrapper);
            for (PmsAttrGroup group : groups) {
                PmsCategory pmsCategory = pmsCategoryMapper.selectById(group.getCategoryId());
                group.setCategoryName(pmsCategory.getName());
            }
            return groups;
        } else {
            Long categoryId = pmsAttrGroup.getCategoryId();
            queryWrapper.eq("category_id", categoryId);
            //select * from pms_attr_group where category_id =? and (id=key or name like %key%)
            List<PmsAttrGroup> groups = pmsAttrGroupMapper.selectList(queryWrapper);
            for (PmsAttrGroup group : groups) {
                PmsCategory pmsCategory = pmsCategoryMapper.selectById(group.getCategoryId());
                group.setCategoryName(pmsCategory.getName());
            }
            return groups;
//        return pmsAttrGroupMapper.selectList(null).stream().map(i -> {
//                PmsCategory pmsCategory = pmsCategoryMapper.selectById(i.getCategoryId());
//                i.setCategoryName(pmsCategory.getName());
//                return i;
//            }).collect(Collectors.toList());

        }
    }

    /**
     * 新增属性分组
     *
     * @param pmsAttrGroup 属性分组
     * @return 结果
     */
    @Override
    public int insertPmsAttrGroup(PmsAttrGroup pmsAttrGroup) {
        return pmsAttrGroupMapper.insert(pmsAttrGroup);
    }

    /**
     * 修改属性分组
     *
     * @param pmsAttrGroup 属性分组
     * @return 结果
     */
    @Override
    public int updatePmsAttrGroup(PmsAttrGroup pmsAttrGroup) {
        return pmsAttrGroupMapper.updateById(pmsAttrGroup);
    }

    /**
     * 批量删除属性分组
     *
     * @param ids 需要删除的属性分组主键
     * @return 结果
     */
    @Override
    public int deletePmsAttrGroupByIds(Long[] ids) {
        return pmsAttrGroupMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除属性分组信息
     *
     * @param id 属性分组主键
     * @return 结果
     */
    @Override
    public int deletePmsAttrGroupById(Long id) {
        return pmsAttrGroupMapper.deleteById(id);
    }

    /**
     * 查询关联关系
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<PmsAttr> selectPmsAttrGroupRelation(Long attrGroupId) {

        List<PmsAttrAttrgroupRelation> relations = pmsAttrAttrgroupRelationMapper.selectList(new QueryWrapper<PmsAttrAttrgroupRelation>().eq("attr_group_id", attrGroupId));
        List<Long> relationIds = relations.stream().map(PmsAttrAttrgroupRelation::getAttrId).collect(Collectors.toList());

        if (StringUtils.isEmpty(relationIds)) {
            return new ArrayList<PmsAttr>();
        }
        List<PmsAttr> list = new ArrayList<>();
        relationIds.forEach(item -> {
            list.add(pmsAttrMapper.selectPmsAttrById(item));
        });

        return list;
    }

    @Override
    public int deletePmsAttrGroupRelation(PmsAttrGroupVo[] pmsAttrGroupVo) {
        int j = 0;
        for (PmsAttrGroupVo attrGroupVo : pmsAttrGroupVo) {
            pmsAttrAttrgroupRelationMapper.delete(new QueryWrapper<PmsAttrAttrgroupRelation>()
                    .eq("attr_id", attrGroupVo.getAttrId())
                    .and(i -> i.eq("attr_group_id", attrGroupVo.getAttrGroupId())));
            j++;
        }
        return j;
    }

    /**
     * 获取当前分组没有关联的
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<PmsAttr> selectPmsAttrGroupRelationNot(PmsAttr pmsAttr, Long attrGroupId) {
        //1.当前分组只能关联自己所属的分类里面的所有属性
        PmsAttrGroup pmsAttrGroup = pmsAttrGroupMapper.selectById(attrGroupId);
        Long categoryId = pmsAttrGroup.getCategoryId();
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1 当前分类下的其他分组
        List<PmsAttrGroup> pmsAttrGroups = pmsAttrGroupMapper.selectList(new QueryWrapper<PmsAttrGroup>().eq("category_id", categoryId));
        List<Long> pmsAttrGroupIds = pmsAttrGroups.stream().map(PmsAttrGroup::getCategoryId).collect(Collectors.toList());
        //2.2 这些分组关联的属性
        List<PmsAttrAttrgroupRelation> attrAttrGroupRelationList = pmsAttrAttrgroupRelationMapper.selectList(new QueryWrapper<PmsAttrAttrgroupRelation>().in("attr_group_id", pmsAttrGroupIds));
        List<Long> attrIds = attrAttrGroupRelationList.stream().map(PmsAttrAttrgroupRelation::getAttrId).collect(Collectors.toList());
        //2.3 从当前分类的所有属性中移除这些属性
        QueryWrapper<PmsAttr> wrapper = new QueryWrapper<PmsAttr>().eq("category_id", categoryId).eq("type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!StringUtils.isEmpty(attrIds)) {
            wrapper.notIn("id", attrIds);
        }
        String key = pmsAttr.getKey();
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("id", key).or().like("name", key));
        }
        List<PmsAttr> list = pmsAttrMapper.selectList(wrapper);

        return list;
    }

    /**
     * 新增关联关系
     *
     * @param pmsAttrGroupVos
     * @return
     */
    @Override
    public int insertPmsAttrGroupRelation(List<PmsAttrGroupVo> pmsAttrGroupVos) {


        Integer i = 0;
        for (PmsAttrGroupVo pmsAttrGroupVo : pmsAttrGroupVos) {
            PmsAttrAttrgroupRelation pmsAttrAttrgroupRelation = new PmsAttrAttrgroupRelation();
            BeanUtils.copyProperties(pmsAttrGroupVo, pmsAttrAttrgroupRelation);
            pmsAttrAttrgroupRelationMapper.insert(pmsAttrAttrgroupRelation);
            ++i;
        }
        return i;


    }

    /**
     * 查询分类下的分组信息 和分组信息所关联的属性信息
     * @param categoryId 分类id
     * @return
     */
    public List<PmsAttrGroupAttrsVo> listWithAttr(Long categoryId) {

        QueryWrapper<PmsAttrGroup> wrapper = new QueryWrapper<PmsAttrGroup>().eq("category_id", categoryId);

        List<PmsAttrGroup> pmsAttrGroups = pmsAttrGroupMapper.selectList(wrapper);
        List<PmsAttrGroupAttrsVo> list = new ArrayList<>();

//        pmsAttrGroups.forEach(pmsAttrGroup -> {
        for (PmsAttrGroup pmsAttrGroup : pmsAttrGroups) {
            PmsAttrGroupAttrsVo pmsAttrGroupAttrsVo = new PmsAttrGroupAttrsVo();
            BeanUtils.copyProperties(pmsAttrGroup, pmsAttrGroupAttrsVo);

            List<PmsAttrAttrgroupRelation> attrAttrgroupRelationList = pmsAttrAttrgroupRelationMapper.selectList(new QueryWrapper<PmsAttrAttrgroupRelation>().eq("attr_group_id", pmsAttrGroup.getId()));
            if(!StringUtils.isEmpty(attrAttrgroupRelationList)){
                List<Long> attrIds = attrAttrgroupRelationList.stream().map(PmsAttrAttrgroupRelation::getAttrId).collect(Collectors.toList());
                List<PmsAttr> pmsAttrList = pmsAttrMapper.selectBatchIds(attrIds);
                pmsAttrGroupAttrsVo.setAttrs(pmsAttrList);
            }else {
                pmsAttrGroupAttrsVo.setAttrs(new ArrayList<>());
            }
            list.add(pmsAttrGroupAttrsVo);
        }


//        });
        return list;

    }
}
